package com.example.cmpe277stockdata.RSSFeeds;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.example.cmpe277stockdata.beans.HistoricalBean;
import com.example.cmpe277stockdata.constants.DataConstants;

public class HistoricalReader 
{
	public ArrayList<HistoricalBean> getHistoricalFields(String companySymbol,String period)
	{
		String todate = "", fromdate = "" ;
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance(); 
		todate = dateFormat.format(cal.getTime()).toString();

		if(period!= null && !period.equals(""))
		{			
			if(period.equals("1 Week"))
			{
			cal.add(Calendar.DAY_OF_YEAR, -7);
			fromdate = dateFormat.format(cal.getTime()).toString();
			}
			else if(period.equals("1 Month"))
			{
			cal.add(Calendar.DAY_OF_YEAR, -30);
			fromdate = dateFormat.format(cal.getTime()).toString();
			}
			else if(period.equals("2 Months"))
			{
			cal.add(Calendar.DAY_OF_YEAR, -60);
			fromdate = dateFormat.format(cal.getTime()).toString();
			}
			else if(period.equals("6 Months"))
			{
			cal.add(Calendar.DAY_OF_YEAR, -130);
			fromdate = dateFormat.format(cal.getTime()).toString();
			}
			else
			{
			cal.add(Calendar.DAY_OF_YEAR, -260);
			fromdate = dateFormat.format(cal.getTime()).toString();
			}
			//System.out.println("todate " + todate + " fromdate " + fromdate);
		}
		//need to put the date
		String URLString = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20%3D%20%22"+companySymbol+"%22%20and%20startDate%20%3D%20%22"+fromdate+"%22%20and%20endDate%20%3D%20%22"+todate+"%22&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
		ArrayList<HistoricalBean> historicalBean = null;
		try {
			
			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			URL u;
		
			u = new URL(URLString);
		
			Document doc = builder.parse(u.openStream());
			NodeList nodes = doc.getElementsByTagName(DataConstants.HISTORICAL_MAIN);
			System.out.println(nodes.getLength());
			historicalBean = new ArrayList<HistoricalBean>();
			for(int i=0;i<nodes.getLength();i++) 
			{
				HistoricalBean data = new HistoricalBean();
				Element element = (Element)nodes.item(i);	
				data.setOpenValue(Double.parseDouble(getElementValue(element,DataConstants.HISTORICAL_OPEN)));
				data.setCloseValue(Double.parseDouble(getElementValue(element,DataConstants.HISTORICAL_CLOSE)));
				data.setLowValue(Double.parseDouble(getElementValue(element,DataConstants.HISTORICAL_LOW)));
				data.setHighValue(Double.parseDouble(getElementValue(element,DataConstants.HISTORICAL_HIGH)));
				data.setStockDate(getElementValue(element,DataConstants.HISTORICAL_DATE));
				data.setVolumneData(Integer.parseInt(getElementValue(element,DataConstants.HISTORICAL_VOLUME)));
				data.setAdjClose(Double.parseDouble(getElementValue(element,DataConstants.HISTORICAL_ADJCLOSE)));
				historicalBean.add(data);
			}
			return historicalBean;
		} 
		catch (MalformedURLException e) 
		{
			System.err.println(e.getMessage());
		} 
		catch (SAXException e) 
		{
			System.err.println(e.getMessage());
		}
		catch (IOException e) 
		{
			System.err.println(e.getMessage());
		} 
		catch (ParserConfigurationException e)
		{
			System.err.println(e.getMessage());
		}
		return historicalBean;
	}

	protected static String getElementValue(Element parent, String label)
	{
		return getCharacterDataFromElement((Element) parent
				.getElementsByTagName(label).item(0));
	}

	private static String getCharacterDataFromElement(Element e) 
	{
		try 
		{
			Node child = e.getFirstChild();
			if (child instanceof CharacterData) {
				CharacterData cd = (CharacterData) child;
				return cd.getData();
			}
		} 
		catch (Exception ex) {
			System.err.println(ex.getMessage());
		}
		return "";
	}
}
